package com.hnas.sys.core.spring;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hnas.core.util.DateUtil;
import com.hnas.core.util.StringUtil;
import com.hnas.sys.dao.LogDAO;
import com.hnas.sys.dao.UserDAO;
import com.hnas.sys.orm.LogInfo;
import com.hnas.sys.orm.User;

public class MyAuthenticationFailureHandler extends
		SimpleUrlAuthenticationFailureHandler implements
		AuthenticationFailureHandler {
	@Autowired
	private LogDAO logDAO;
//	@Autowired
//	private ObjectTypeDAO objectTypeDAO;
	@Autowired
	private UserDAO userDAO;
	private int maxLoginFalure = 5;

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException exception)
			throws ServletException, IOException {
		// 这里填写自己要执行的操作 如用户的登录时间、ip等等。
		super.onAuthenticationFailure(request, response, exception);
		if(exception.getMessage().indexOf("验证码")>=0){
			request.getSession().setAttribute("loginfail", exception.getMessage());
		}else{
			request.getSession().setAttribute("loginfail", "用户名或密码不正确");
		}
		
		if (null != exception.getMessage()
				&& (exception.getMessage().indexOf("Bad credentials") >= 0 || exception.getMessage().equals("User is disabled"))) {//登录失败
			String loginName = request.getParameter("j_username");
			if (!StringUtil.isEmpty(loginName)) {
				// START 20180419 ADD FOR 以用户输入的验证码作为key，使用AES算法解密账户
				String jcaptchaCode = UsernamePasswordAuthenticationExtendFilter
						.obtainValidateCodeParameter(request);
				loginName = UsernamePasswordAuthenticationExtendFilter
						.aesEncrypt(loginName, jcaptchaCode);
				// END
				User operator = this.userDAO.findByUserName(loginName.trim());
				if (null != operator) {
//					ObjectType object = this.objectTypeDAO
//							.getObjectByCode("User");
//					// if (null==object)
//					// throw new CommonException("找不到实体对象，请与系统管理员联系！");
					LogInfo log = new LogInfo();
					log.setOperator(operator);
					log.setObjectType(User.class.getSimpleName());
					log.setObjectId(operator.getId());
					log.setLogInfo("登录失败，ip:" + request.getRemoteAddr()+"；"+exception.getMessage()+"；用户状态："+operator.getStatusStr());
					log.setOperateTime(DateUtil.dateTimeToString(new Date()));
					log.setOperateType("loginFailure");
					this.logDAO.persist(log);
//					//登录失败次数
//					operator.setLoginFailure(operator.getLoginFailure()+1);
//					if (operator.getLoginFailure()>=this.maxLoginFalure){
//						//锁定帐户
//						operator.setStatus(UserStatus.INVALID);
//					}
					operator.setLastLogin(DateUtil.dateTimeToString(new Date()));
					this.userDAO.merge(operator);
				}
			}

//			HttpSession session = request.getSession(false);
//			if (null!=session){
//				logger.error("athen Session1:"+session.getId());
//				session.invalidate();//清空session
//				if (null!=request.getCookies() && request.getCookies().length>0){
//					Cookie cookie = request.getCookies()[0];//获取cookie
//			    	cookie.setMaxAge(0);//让cookie过期
//				}
//			}
//			request.getSession(true);
			
			String msg = exception.getMessage(); 
			if (null!=msg && msg.startsWith("非法访问")){
				response.sendError(403);
				response.getWriter().close();
				return ;
			}
//			 session =request.getSession(true);
//			logger.error("athen Session2:"+session.getId());
		}
	}

	public LogDAO getLogDAO() {
		return logDAO;
	}

	public void setLogDAO(LogDAO logDAO) {
		this.logDAO = logDAO;
	}

	

	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public int getMaxLoginFalure() {
		return maxLoginFalure;
	}

	public void setMaxLoginFalure(int maxLoginFalure) {
		this.maxLoginFalure = maxLoginFalure;
	}

}
